package com.example.wuyeguanli.activity;

import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.example.wuyeguanli.R;
import com.example.wuyeguanli.tools.ApiClient;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.not;

@RunWith(AndroidJUnit4.class)
public class RepairlistActivityTest {

    private static MockWebServer mockWebServer; // 改为static

    private static String originalBaseUrl; // 用于在测试后恢复原始URL

    @BeforeClass
    public static void setUpClass() throws IOException {
        // 1. 保存原始URL
        originalBaseUrl = ApiClient.BASE_URL;

        // 2. 启动MockWebServer
        mockWebServer = new MockWebServer();
        mockWebServer.start(8080); // 依然在8080端口启动

        // 3. 核心修正: 动态设置ApiClient的URL指向我们的MockWebServer
        //    MockWebServer.url("/") 会返回类似 "http://localhost:8080/" 的地址
        ApiClient.setBaseUrlForTesting(mockWebServer.url("/").toString());
    }

    @AfterClass
    public static void tearDownClass() throws IOException {
        if (mockWebServer != null) {
            mockWebServer.shutdown();
        }
        // 恢复原始的BASE_URL，避免影响其他测试类
        ApiClient.setBaseUrlForTesting(originalBaseUrl);
    }

    @Test
    public void testSearchAndDisplayRepairs_Success() {
        // 1. 准备包含两条报修记录的Mock响应
        String jsonResponse = "{\"state\":\"success\",\"error\":\"\",\"data\":[" +
                "{\"workOrderId\":\"R20240101001\",\"message\":\"水龙头漏水\",\"imageId\":null,\"handled\":false,\"roomNumber\":\"101\"}," +
                "{\"workOrderId\":\"R20240101002\",\"message\":\"电灯不亮\",\"imageId\":null,\"handled\":true,\"roomNumber\":\"101\"}" +
                "]}";
        mockWebServer.enqueue(new MockResponse().setBody(jsonResponse));

        // 2. 启动Activity
        ActivityScenario.launch(RepairlistActivity.class);

        // 3. 模拟用户操作
        onView(withId(R.id.edit_room)).perform(typeText("101101"), closeSoftKeyboard());
        onView(withId(R.id.btn_search)).perform(click());

        // 4. 断言：验证RecyclerView中显示了正确的数据
        // 验证第一项
        onView(withId(R.id.recyclerView)).perform(RecyclerViewActions.scrollToPosition(0));
        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(0))
                .check(matches(hasDescendant(allOf(withId(R.id.repair_num), withText("R20240101001")))));
        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(0))
                .check(matches(hasDescendant(allOf(withId(R.id.repair_boolean), withText("待处理")))));
        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(0))
                .check(matches(hasDescendant(allOf(withId(R.id.repair_buttom), isDisplayed())))); // 完成按钮可见

        // 验证第二项
        onView(withId(R.id.recyclerView)).perform(RecyclerViewActions.scrollToPosition(1));
        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(1))
                .check(matches(hasDescendant(allOf(withId(R.id.repair_num), withText("R20240101002")))));
        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(1))
                .check(matches(hasDescendant(allOf(withId(R.id.repair_boolean), withText("已完成")))));
        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(1))
                .check(matches(hasDescendant(allOf(withId(R.id.repair_buttom), not(isDisplayed()))))); // 完成按钮不可见
    }
}